package com.zhangyx.core;

import com.zhangyx.comm.ThreadUtil;
import org.apache.log4j.Logger;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class TaskManager {
    private static Logger log = Logger.getLogger(TaskManager.class);

    public static ExecutorService startTask(Class ob, int nThreads) {
        ExecutorService es = Executors.newFixedThreadPool(nThreads + 1);
        Thread worker = null;
        try {
            worker = (Thread) ob.newInstance();
        } catch (Exception e) {
            log.error("创建线程实例出错");
        }
        for (int i = 0; i < nThreads; i++) {
            es.execute(worker);
        }
        log.info("线程池启动成功");
        // 监控
        es.execute(new Runnable() {
            public void run() {
                while (!Thread.interrupted()) {
                    ThreadGroup group = Thread.currentThread().getThreadGroup();
                    Thread[] list = new Thread[group.activeCount()];
                    group.enumerate(list);
                    for (Thread th : list) {
                        if (th != null) {
                            log.info(th.toString()+":"+th.getState().name());
                        }
                    }
                    ThreadUtil.sleepMills(1000 * 60 * 30);
                }
            }
        });
        shutdownWhenExit(es);
        return es;
    }

    private static void shutdownWhenExit(final ExecutorService es) {
        Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override
            public void run() {
                try {
                    if (es != null) {
                        es.shutdownNow();
                    }
                } catch (Exception e) {
                    log.error("关闭线程池出错");
                }
            }
        });
    }
}
